package com.mce.nebula.service;

import com.mce.nebula.common.UuidGenerator;
import com.mce.nebula.dto.AppGroupCreateRequest;
import com.mce.nebula.entity.AppGroup;
import com.mce.nebula.entity.TenantService;
import com.mce.nebula.repository.AppGroupRepository;
import com.mce.nebula.repository.TenantServiceRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 应用组服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AppGroupService {
    
    private final AppGroupRepository appGroupRepository;
    private final TenantServiceRepository tenantServiceRepository;
    
    /**
     * 创建应用组
     */
    @Transactional
    public AppGroup createAppGroup(AppGroupCreateRequest request, String tenantId, Integer creatorId, String enterpriseId) {
        // 检查组名是否已存在
        if (appGroupRepository.existsByTenantIdAndGroupName(tenantId, request.getGroupName())) {
            throw new RuntimeException("应用组名称已存在");
        }
        
        // 生成组ID和组Key
        String groupId = UuidGenerator.makeUuid();
        String groupKey = UuidGenerator.makeUuid().substring(0, 16);
        
        // 创建应用组
        AppGroup appGroup = new AppGroup();
        appGroup.setGroupId(groupId);
        appGroup.setTenantId(tenantId);
        appGroup.setGroupName(request.getGroupName());
        appGroup.setGroupAlias(request.getGroupAlias());
        appGroup.setGroupKey(groupKey);
        appGroup.setRegionName(request.getRegionName());
        appGroup.setDescription(request.getDescription());
        appGroup.setCreater(creatorId);
        appGroup.setIsPublic(request.getIsPublic());
        appGroup.setIsGovernance(request.getIsGovernance());
        appGroup.setGovernanceMode(request.getGovernanceMode());
        appGroup.setEnterpriseId(enterpriseId);
        
        AppGroup savedAppGroup = appGroupRepository.save(appGroup);
        
        log.info("App group created: {} by user: {}", request.getGroupName(), creatorId);
        return savedAppGroup;
    }
    
    /**
     * 根据组ID查找应用组
     */
    public Optional<AppGroup> findByGroupId(String groupId) {
        return appGroupRepository.findByGroupId(groupId);
    }
    
    /**
     * 根据租户ID查找应用组列表
     */
    public List<AppGroup> getTenantAppGroups(String tenantId) {
        return appGroupRepository.findByTenantId(tenantId);
    }
    
    /**
     * 根据租户ID和组名查找应用组
     */
    public Optional<AppGroup> findByTenantIdAndGroupName(String tenantId, String groupName) {
        return appGroupRepository.findByTenantIdAndGroupName(tenantId, groupName);
    }
    
    /**
     * 获取应用组下的服务列表
     */
    public List<TenantService> getAppGroupServices(String groupId) {
        return tenantServiceRepository.findByTenantIdAndTenantServiceGroupId(
            appGroupRepository.findByGroupId(groupId)
                .map(AppGroup::getTenantId)
                .orElse(""), 
            Integer.parseInt(groupId.substring(0, Math.min(groupId.length(), 8)), 16)
        );
    }
    
    /**
     * 删除应用组
     */
    @Transactional
    public void deleteAppGroup(String groupId) {
        AppGroup appGroup = appGroupRepository.findByGroupId(groupId)
            .orElseThrow(() -> new RuntimeException("应用组不存在"));
        
        // 检查是否有服务在使用该组
        List<TenantService> services = getAppGroupServices(groupId);
        if (!services.isEmpty()) {
            throw new RuntimeException("应用组下还有服务，无法删除");
        }
        
        appGroupRepository.delete(appGroup);
        log.info("App group deleted: {}", appGroup.getGroupName());
    }
    
    /**
     * 更新应用组信息
     */
    @Transactional
    public AppGroup updateAppGroup(String groupId, AppGroupCreateRequest request) {
        AppGroup appGroup = appGroupRepository.findByGroupId(groupId)
            .orElseThrow(() -> new RuntimeException("应用组不存在"));
        
        // 如果组名发生变化，检查新名称是否已存在
        if (!appGroup.getGroupName().equals(request.getGroupName()) && 
            appGroupRepository.existsByTenantIdAndGroupName(appGroup.getTenantId(), request.getGroupName())) {
            throw new RuntimeException("应用组名称已存在");
        }
        
        appGroup.setGroupName(request.getGroupName());
        appGroup.setGroupAlias(request.getGroupAlias());
        appGroup.setDescription(request.getDescription());
        appGroup.setIsPublic(request.getIsPublic());
        appGroup.setIsGovernance(request.getIsGovernance());
        appGroup.setGovernanceMode(request.getGovernanceMode());
        
        return appGroupRepository.save(appGroup);
    }
}





